#include <iostream>
#include <cmath>

/** 
 * Get the r-th digit of A in octal sys.
 * 
 * @param A The object natural number.
 * @param r The r-th digit.
 * 
 * @return The digit number.
 */
int digit(int A, int r);

int digit(int A, int r)
{
    int oct = r * 3;
    return (A & (7 << oct)) >> oct;
};

int main(int argc, char* argv[])
{
    int n = 7;
    int k = 8;
    int A[] = {329, 457, 657, 839, 436, 720, 355};
    int C[k];
    int B[n];
    for (int r = 0; r < 4; r++)
    {
	for (int i = 0; i < k; i++)
	    C[i] = 0;
	for (int j = 0; j < n; j++)
	{
	    int d = digit(A[j], r);
	    C[d] = C[d] + 1;
	}
	for (int i = 1; i < k; i++)
	    C[i] = C[i] + C[i - 1];
	for (int j = n - 1; j >=0; j--)
	{
	    int d = digit(A[j], r);
	    B[C[d] - 1] = A[j];
	    C[d] = C[d] - 1;
	}
	for (int i = 0; i < n; i++)
	    A[i] = B[i];
    }
    std::cout << "B = [";
    for (int i = 0; i < n; i++)
	std::cout << B[i] << ", ";
    std::cout << "\b\b]" << std::endl;
    return 0;
};
